package cn.fl.infside.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.infside.service.IInfWarrantProjectService;
import cn.fl.infside.transform.InfWarrantProjectVOTransform;
import cn.fl.infside.vo.InfWarrantProjectVO;
import cn.fl.system.constant.SysLogConstant;
import fl.inf.facade.condition.InfWarrantProjectQueryCondition;
import fl.inf.facade.constant.InterfaceConstants;
import fl.inf.facade.dto.InfWarrantProjectDTO;
import fl.inf.facade.dto.MessageDTO;

/**
 * @Description: 权证系统项目接口表 控制层
 */
@Controller
@RequestMapping("/infside/infWarrantProject")
public class InfWarrantProjectController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InfWarrantProjectController.class);

	/**
	 * InfWarrantProject 服务层BEAN
	 */
	@Autowired
	private IInfWarrantProjectService infWarrantProjectService;

	/**
	 * 到权证管理首页
	 */
	@RequestMapping(value = "/toInfWarrantPage.do", method = { RequestMethod.GET})
	public ModelAndView toInfWarrantPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/infWarrantProject/infWarrantPage");
		BaseLogUtils.info(logger, "toInfWarrantPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}


	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toInfWarrantProjectList.do", method = { RequestMethod.GET})
	public ModelAndView toInfWarrantProjectList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/infWarrantProject/infWarrantProjectList");
		List<Map<String,String>> statuslist = new ArrayList<Map<String,String>>();
		for(InterfaceConstants.InterfaceStatus status : InterfaceConstants.InterfaceStatus.values()){
			Map<String,String> statusmap = new HashMap<String,String>();
			statusmap.put("key",status.key());
			statusmap.put("value",status.desc());
			statuslist.add(statusmap);
		}
		List<KeyValueVO> prjtypelist = this.infWarrantProjectService.getKvList(DictionaryConstant.CODE_PRJ_TYPE_CD, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("prjtypelist", prjtypelist);
		view.addObject("statuslist", statuslist);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("infside/infWarrantProject/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initInfWarrantProjectList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initInfWarrantProjectList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String projectName = request.getParameter("projectName"); //项目名称
		String customerName = request.getParameter("customerName"); //客户名称
		String provincialCompany = request.getParameter("provincialCompany"); //省公司
		String status = request.getParameter("status"); //状态
		String projectType = request.getParameter("projectType"); //项目类型

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		InfWarrantProjectQueryCondition qc = new InfWarrantProjectQueryCondition();
		if (StringUtils.isNotEmpty(projectName)) {
			qc.setProjectName(projectName);
		}
		if (StringUtils.isNotEmpty(customerName)) {
			qc.setCustomerName(customerName);
		}
		if (StringUtils.isNotEmpty(provincialCompany)) {
			qc.setProvincialCompany(provincialCompany);
		}
		if (StringUtils.isNotEmpty(status)) {
			qc.setStatus(status);
		}
		if (StringUtils.isNotEmpty(projectType)) {
			qc.setProjectType(projectType);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.infWarrantProjectService.searchListPage(page);
		List<InfWarrantProjectVO> list = InfWarrantProjectVOTransform.toVOList((List<InfWarrantProjectDTO>) pager.getResultList());
		for(InfWarrantProjectVO _vo : list){
			if(StringUtils.isNotEmpty(_vo.getStatus())){
				for(InterfaceConstants.InterfaceStatus _enumstatus : InterfaceConstants.InterfaceStatus.values()){
					if(StringUtils.isNotEmpty(_enumstatus.key()) && (_vo.getStatus()).equals(_enumstatus.key())){
						_vo.setStatusNm(_enumstatus.desc());
						break;
					}
				}
			}
			if(StringUtils.isNotEmpty(_vo.getOrgNo())){
				_vo.setOrgNo(this.infWarrantProjectService.searchOrgNm(_vo.getOrgNo(), CurrentThreadContext.getFlServiceSysCd()));
			}
			if(StringUtils.isNotEmpty(_vo.getProvincialCompany())){
				_vo.setProvincialCompany(this.infWarrantProjectService.searchOrgNm(_vo.getProvincialCompany(), CurrentThreadContext.getFlServiceSysCd()));
			}
			/**
			 * 客户编号不用
			if(null != _vo.getCustomerId()){
				CstBscInfoVO cstvo = this.infWarrantProjectService.searchCstBscInfoDetail(_vo.getCustomerId());
				if(null != cstvo && StringUtils.isNotEmpty(cstvo.getCstCd())){
					_vo.setCustomerCode(cstvo.getCstCd());
				}
			}
			 **/
			if(StringUtils.isNotEmpty(_vo.getCustomerType())){
				Map<String, String> csttypMap = this.infWarrantProjectService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_CST_TYP_CD);
				_vo.setCustomerType(csttypMap.get(_vo.getCustomerType()));
			}
			if(StringUtils.isNotEmpty(_vo.getBusinessType())){
				Map<String, String> biztypMap = this.infWarrantProjectService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_SYS_BUSINESS_TYP_CD);
				_vo.setBusinessType(biztypMap.get(_vo.getBusinessType()));
			}
			if(StringUtils.isNotEmpty(_vo.getProjectNature())){
				//TODO 需要修改成查询数据字典的项目性质
				Map<String, String> projectpropertyMap = new HashMap<String, String>();
				projectpropertyMap.put("1","新增");
				projectpropertyMap.put("2","续签");
				_vo.setProjectNature(projectpropertyMap.get(_vo.getProjectNature()));
			}
			if(null != _vo.getContractPayment()){
				_vo.setContractPaymentdou(DecimalUtils.convertFenToYuan(_vo.getContractPayment()));
			}
		}
		ListPageVO<InfWarrantProjectVO> listPage = new ListPageVO<InfWarrantProjectVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initInfWarrantProjectList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.infWarrantProjectService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InfWarrantProjectVO vo = this.infWarrantProjectService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		InfWarrantProjectVO entity = null;
		try {
			entity = new InfWarrantProjectVO();
			//TODO ADD PARAM
			Long id = this.infWarrantProjectService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		InfWarrantProjectVO entity = null;
		try {
			entity = new InfWarrantProjectVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.infWarrantProjectService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 *组织机构信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchOrgTree.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object searchOrgTree(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		try {

			JSONArray array = new JSONArray();
			array = this.infWarrantProjectService.searchOrgTreeByCurrentUser(CurrentThreadContext.getCurrentOrgCd(), CurrentThreadContext.getFlServiceSysCd());
			if(null == array){
				array = new JSONArray();
			}

			result.setData(array);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}

	/**
	 * 发送项目
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/projectApply.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object projectApply(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String projectId = request.getParameter("projectId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "发送完成");
		if(StringUtils.isEmpty(projectId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "projectApply", "projectId空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			MessageDTO<String> messagedto = this.infWarrantProjectService.projectApply(Long.valueOf(projectId));
			if(!messagedto.isSuccess()){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				//result.setInfo(messagedto.getMessage());
				result.setInfo("发送失败");
				BaseLogUtils.info(logger, "projectApply", "发送失败", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("发送失败！");
			logger.error("发送失败！", ex);
		}
		return result;
	}
}

